local System = require"ecs/system/system"
local Zlist = require"module.render.zlist"

--[[
    screen
    2d
    voxel
    tile
--]]

local base_render_system = class("BaseRenderSystem",System){
    system_config = {
        type = SYSYTEM_TYPE_PROCESS;
        is_default_add = false;
        filter = {"RendererComponent"};
        render_priority = 0;
    },

    zlist = nil,
    camera = nil;
}

function base_render_system:_init()
    self.zlist = Zlist()
    self.camera = box_core.get_shared("Camera")
end

function base_render_system:onAddToWorld()
    box_core.callback:register("draw",self,"draw",self.system_config.render_priority)
end

function base_render_system:get_render_z_index(renderer)
    if renderer.inherit_z_index then
        return renderer.bind_entity.z_index + renderer.z_index
    end
    return renderer.z_index 
end

function base_render_system:onAdd(renderer)
    self.zlist:add(self:get_render_z_index(renderer),renderer)
end

function base_render_system:onRemove(renderer)
    self.zlist:remove(self:get_render_z_index(renderer),renderer)
end

function base_render_system:process(renderer,dt)
    local z_index = math.ceil(self:get_render_z_index(renderer))
    local up_z_index = renderer._up_z_index or math.huge
    if up_z_index ~= z_index then
        renderer._up_z_index = z_index
        local old_seg = self.zlist:get_segment(up_z_index)
        local new_seg = self.zlist:get_segment(z_index)
        old_seg:remove(renderer)
        new_seg:add(z_index,renderer)
    end
end

function base_render_system:draw()

end

return base_render_system

